<?php 

class MyCurl
{
	private $url ;   //API地址
	private $ch ;    //curl对象
	private $data = [] ;   //API参数
	private $info  ;   //curl执行信息
	//初始化
	public function __construct($url='',$param=[])
	{
		//判断参数不为空
		if(!empty($url))
		{
			$this->url = $url ;
		}

		if(!empty($param))
		{
			$this->data = $param ;
		}

		$this->ch  = curl_init();
		//默认不输出
		curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
	}

	/**
    *魔术方法,赋值
	*/
	public function __set($name,$value)
	{
		$this->$name = $value;
	}

	/**
	* 魔术方法,类获取私有属性
	*/
	public function __get($name)
	{
		return $this->$name ;
	}

	/**
	* 接口url和参数验证
	* @return boolean
	*/
	private function validateParam()
	{
		try
		{
			if(empty($this->url))
			{
				throw new Exception('接口的url不能为空');
			}

			if(empty($this->data))
			{
				throw new Exception('接口参数不能为空');
			}

			return true ;

		}
		catch(Exception $e)
		{
			echo $e->getMessage();
			return false ;
		}
	}

	/*
	*调用get类型的API接口
	*/
	public function get()
	{
		if ($this->validateParam()) 
		{
			//方法一:file_get_contents();
	/*		$fullurl = $this->url.'?'.$param ;
			return file_get_contents($fullurl);*/
			//方法二:curl
			//获取完成的Url地址
			$fullUrl = $this->handleParam($this->data);
			//初始化地址
			curl_setopt($this->ch, CURLOPT_URL, $fullUrl);

			return $this->exec();
		}

	}

	/*
    *调用post类型的API接口
	*/
	public function post()
	{
		if($this->validateParam())
		{
			//初始化地址
			curl_setopt($this->ch, CURLOPT_URL, $this->url);

			curl_setopt($this->ch, CURLOPT_POST, true) ; 

			curl_setopt($this->ch, CURLOPT_POSTFIELDS, $this->data);
			
			return $this->exec();
		}

 	}

 	/**
 	*执行curl
 	*/
 	private function exec()
 	{
 		try
 		{
		    $res = curl_exec($this->ch);
	        //最后一次curl操作的错误号,返回错误号或0(表示没有错误)
 			if(curl_errno($this->ch))
 			{
 				throw new Exception(curl_error($this->ch));   //获取错误消息
 			}
 			//没有错误,存入获取执行过程的详细信息
 			$this->info = curl_getinfo($this->ch);

			return $res ;
 			
 		}
 		catch(Exception $e)
 		{
 			echo $e->getMessage();
            return false ;
 		}
 	}

	/**
    *处理参数,拼接形成完整的Url
    *@param  $param  参数
    *@return 字符串
	*/
	private function handleParam($param)
	{
		if(is_array($param)&&count($param)>0)
		{
			$paramStr = '' ;
			foreach ($param as $k=>$v) 
			{
				$paramStr .= $k.'='.$v.'&' ;
			}

			return $this->url.'?'.substr($paramStr, 0,-1);
		}
		else
		{
			//get方式提交的数据
			return $this->url.'?'.$param ;
		}
	}

	public function __destruct()
	{
		curl_close($this->ch);
	}

}













 ?>